import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/bloc/chat_cubit.dart';
import 'package:grint/bloc/follow_cubit.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:url_launcher/url_launcher.dart';

class AuthPage extends StatefulWidget {
  const AuthPage({super.key});

  @override
  State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

  void _handleTabChange() {
    if (mounted) setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      animationDuration: const Duration(milliseconds: 150),
    );
    _tabController.addListener(_handleTabChange);
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  // 登录页面UI
  Widget _buildLoginTab() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 用户名输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _usernameController,
                decoration: InputDecoration(
                  hintText: 'User Name',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                ),
              ),
            ),
            SizedBox(height: 16.h),

            // 密码输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: 'Password',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                ),
              ),
            ),
            SizedBox(height: 40.h),

            // 登录按钮
            Container(
              height: 56.h,
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFF6EE2F5), Color(0xFF6454F0)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: TextButton(
                onPressed: () async {
                  // 处理登录逻辑
                  final success = await context.read<AuthCubit>().login(
                    _usernameController.text,
                    _passwordController.text,
                    onLoginSuccess: () {
                      // 登录成功后刷新相关数据
                      _refreshDataAfterLogin();
                    },
                  );

                  if (success && mounted) {
                    // 登录成功后返回上一页
                    context.pop();
                  }
                },
                style: TextButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.transparent,
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                child: MyText(
                  text: "Log In",
                  type: TextType.miSans,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w900,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox(height: 16.h),

            // Apple 登录按钮
            Container(
              height: 56.h,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: TextButton.icon(
                onPressed: () async {
                  // 处理 Apple 登录
                  final credential = await SignInWithApple.getAppleIDCredential(
                    scopes: [
                      AppleIDAuthorizationScopes.email,
                      AppleIDAuthorizationScopes.fullName,
                    ],
                  );

                  context.read<AuthCubit>().login('1001', '123456');
                },
                style: TextButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.transparent,
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                icon: Icon(Icons.apple, color: Colors.white, size: 24.sp),
                label: Text(
                  'Continue with Apple',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
            SizedBox(height: 24.h),

            Container(
              width: double.infinity,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'By continuing, you agree to our ',
                      style: TextStyle(fontSize: 10.sp, color: Colors.grey),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await launchUrl(
                          Uri.parse(
                            'https://www.freeprivacypolicy.com/live/318cba43-6245-4df5-b64d-c9b31c4ac205',
                          ),
                          mode: LaunchMode.inAppBrowserView,
                        );
                      },
                      child: Text(
                        'Terms of Service',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                    Text(
                      ' and ',
                      style: TextStyle(fontSize: 10.sp, color: Colors.grey),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await launchUrl(
                          Uri.parse(
                            'https://www.freeprivacypolicy.com/live/59097e95-a3c0-4157-9233-a2c444911c33',
                          ),
                          mode: LaunchMode.inAppBrowserView,
                        );
                      },
                      child: Text(
                        'Privacy Policy',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 注册页面UI
  Widget _buildRegisterTab() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 用户名输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _usernameController,
                decoration: InputDecoration(
                  hintText: 'User Name',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                ),
              ),
            ),
            SizedBox(height: 16.h),

            // 密码输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: 'Password',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                ),
              ),
            ),
            SizedBox(height: 16.h),

            // 确认密码输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _confirmPasswordController,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: 'Password Again',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                ),
              ),
            ),
            SizedBox(height: 40.h),

            // 注册按钮
            Container(
              height: 56.h,
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFF6EE2F5), Color(0xFF6454F0)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: TextButton(
                onPressed: () async {
                  // 处理注册逻辑
                  final success = await context.read<AuthCubit>().register(
                    _usernameController.text,
                    _passwordController.text,
                    _confirmPasswordController.text,
                    onRegisterSuccess: () {
                      // 注册成功后刷新相关数据
                      _refreshDataAfterLogin();
                    },
                  );

                  if (success && mounted) {
                    // 注册成功后返回上一页
                    context.pop();
                  }
                },
                style: TextButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.transparent,
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                child: Text(
                  'Register',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            SizedBox(height: 24.h),

            SizedBox(
              width: double.infinity,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'By continuing, you agree to our ',
                      style: TextStyle(fontSize: 10.sp, color: Colors.grey),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await launchUrl(
                          Uri.parse(
                            'https://www.freeprivacypolicy.com/live/318cba43-6245-4df5-b64d-c9b31c4ac205',
                          ),
                          mode: LaunchMode.inAppBrowserView,
                        );
                      },
                      child: Text(
                        'Terms of Service',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                    Text(
                      ' and ',
                      style: TextStyle(fontSize: 10.sp, color: Colors.grey),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await launchUrl(
                          Uri.parse(
                            'https://www.freeprivacypolicy.com/live/59097e95-a3c0-4157-9233-a2c444911c33',
                          ),
                          mode: LaunchMode.inAppBrowserView,
                        );
                      },
                      child: Text(
                        'Privacy Policy',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景图
          Image.asset(
            'assets/images/login-bg.png',
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),

          // 页面内容
          SafeArea(
            bottom: false,
            child: Column(
              children: [
                // 顶部返回按钮
                Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: 16.w),
                    child: GestureDetector(
                      onTap: () => context.pop(),
                      child: BlackButton(icon: IconFontIcons.iconArrowLeft),
                    ),
                  ),
                ),
                SizedBox(height: 143.h),
                Expanded(
                  child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      color: const Color(0xFFFFFFFF),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(40.r),
                        topRight: Radius.circular(40.r),
                      ),
                    ),
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Positioned(
                          top: -150.h,
                          left: 0,
                          right: 0,
                          child: Center(
                            child: Image.asset(
                              'assets/images/guzhang.png',
                              width: 172.w,
                              height: 243.h,
                              fit: BoxFit.contain,
                            ),
                          ),
                        ),
                        // 主要内容区域
                        Column(
                          children: [
                            Padding(
                              padding: EdgeInsets.fromLTRB(
                                20.w,
                                100.h,
                                20.w,
                                0,
                              ),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: GestureDetector(
                                      onTap: () {
                                        _tabController.animateTo(0);
                                      },
                                      child: Container(
                                        padding: EdgeInsets.only(bottom: 8.h),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(
                                              width: 2.h,
                                              color: Colors.transparent,
                                            ),
                                          ),
                                        ),
                                        child: MyText(
                                          text: 'Log In',
                                          type: TextType.rubik,
                                          fontSize:
                                              _tabController.index == 0
                                                  ? 30.sp
                                                  : 20.sp,
                                          color: Colors.black,
                                          textAlign: TextAlign.center,
                                        ),
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 16.w),
                                  Expanded(
                                    child: GestureDetector(
                                      onTap: () {
                                        _tabController.animateTo(1);
                                      },
                                      child: Container(
                                        padding: EdgeInsets.only(bottom: 8.h),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(
                                              width: 2.h,
                                              color: Colors.transparent,
                                            ),
                                          ),
                                        ),
                                        child: MyText(
                                          text: 'Register',
                                          type: TextType.rubik,
                                          fontSize:
                                              _tabController.index == 1
                                                  ? 30.sp
                                                  : 20.sp,
                                          color: Colors.black,
                                          textAlign: TextAlign.center,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height: 36.h),

                            Expanded(
                              child: TabBarView(
                                controller: _tabController,
                                physics: const ClampingScrollPhysics(),
                                children: [
                                  // 登录页面
                                  _buildLoginTab(),
                                  // 注册页面
                                  _buildRegisterTab(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 登录成功后刷新相关数据
  void _refreshDataAfterLogin() {
    final authState = context.read<AuthCubit>().state;
    if (authState.isLoggedIn && authState.currentUser != null) {
      // 刷新聊天数据
      context.read<ChatCubit>().loadUserConversations(
        authState.currentUser!.id,
      );

      // 刷新关注数据
      context.read<FollowCubit>().refreshFollowingUsers();

      // 刷新内容数据
      context.read<ContentCuratorCubit>().refreshContent();
    }
  }
}
